<?php
/**
 * Description of IndexController
 *
 * @author minhhq
 */
class IndexController extends MKT_Controller_Action {
    public function indexAction() {
        $fb_params = Core_Util::getConfig("facebook");
        $this->view->fb_params = $fb_params;
    }
    
    public function postauthorizeAction() {
        $id_social_page = $this->_getTabAddedId();
        if (empty($id_social_page)) {
            return;
        }
        $has_authorized = $this->_facebook->hasAuthorized();
        if (!$has_authorized) {
            $url = $this->view->baseUrl() . '/default/index/postauthorize/pid/' . $id_social_page;
            $server_url = $this->view->serverUrl($url); 
            $scope = $this->_facebook->getScope();            
            $params = array (
                'scope'         => $scope,
                'redirect_uri'  => $server_url
            );
            $login_url = $this->_facebook->getLoginUrl($params);
            $this->_redirect($login_url);
        } else {   
            $page_db = new Core_Model_DbTable_Pages();
            $page_db->insertDefault($id_social_page);
            
            $this->_facebook->registerRealtimeUpdate($id_social_page);
            $tab_url = $this->_facebook->getAppTabUrl($id_social_page);
            
            $this->_redirect($tab_url);
        }
    }
    
    protected function _getTabAddedId() {
        $result = NULL;
        $pid = $this->_getParam("pid");
        if (!empty($pid)) {
            $result = $this->_getParam("pid");
        } else {
            $param = $this->_getParam("tabs_added");
            if (is_array($param)) {
                $tabs_added_ids = array_keys($param);
                $result = $tabs_added_ids[0];
            }
        }
        return $result;
    }
    
    public function shareAction() {
        $id_social_page = $this->_getParam("pid");
        if (!MKT_Util::isFacebookRequest()) {
            $this->_redirect(FACEBOOK_URL . "?sk=app_{$this->_facebook->getAppId()}");
        } else {
            $page_db = new Core_Model_DbTable_Pages();
            $page_info = $page_db->getPageInfo($id_social_page);
            $this->view->id_social_page = $id_social_page;
            $this->view->url = $this->_facebook->url("/topfans/share/pid/" + $id_social_page);
            $this->view->image = "/images/icon.png";           
            $this->view->app_id = $this->_facebook->getAppId();
            $this->view->title = 'Top Fans';
            $this->view->desciption = $page_info->description;
        }
    }
}

?>
